package com.db.person.controller;

import com.db.person.bean.*;
import com.db.person.service.*;
import com.db.person.util.PageModel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@Controller
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private ISexService sexService;
    
    @Autowired
    private IEducationService educationService;
    
    @Autowired
    private IJobService jobService;
    
    @Autowired
    private IDeptService deptService;

    @RequestMapping("/employee/toadd")
    public String toadd(Model model){

        List<Sex> sexAll = sexService.getAll();
        List<Education> eduAll = educationService.getAll();
        List<Dept> deptAll = deptService.getAll();
        List<Job> jobAll = jobService.getAll();

        model.addAttribute("sex_list",sexAll);
        model.addAttribute("education_list",eduAll);
        model.addAttribute("job_list",jobAll);
        model.addAttribute("dept_list",deptAll);

        return "employee/add";
    }

    @RequestMapping("/employee/add")
    public String add(Employee employee){

        //调用service  mapper  插入到数据库
        employeeService.insert(employee);

        return "redirect:/employee/list";
    }

    @RequestMapping("/employee/list")
    public String toList(Model model, PageModel pageModel){

        PageHelper.startPage(pageModel.getPageIndex(),pageModel.getPageSize());
        //查询所有的员工
        List<Employee> all = employeeService.getAll();

        PageInfo<Employee> pageInfo = new PageInfo<>(all);

        long total = pageInfo.getTotal();//总条数
        pageModel.setRecordCount((int)total);

        List<Employee> list = pageInfo.getList();//得到当前页的数据
        model.addAttribute("list",list);//展示的数据
        model.addAttribute("pageModel",pageModel);//前端需要分页的参数
        model.addAttribute("hre","employee/list");//分页跳转的路径
        return "employee/list";
    }

    @RequestMapping("/employee/toedit")
    public String toEdit(Integer id, Model model){

        //根据id查询employee的数据
        Employee emp = employeeService.getById(id);
        model.addAttribute("employee",emp);

        //以下类似添加页面需要对应的下拉框的值
        List<Sex> sexAll = sexService.getAll();
        List<Education> eduAll = educationService.getAll();
        List<Dept> deptAll = deptService.getAll();
        List<Job> jobAll = jobService.getAll();

        model.addAttribute("sex_list",sexAll);
        model.addAttribute("education_list",eduAll);
        model.addAttribute("job_list",jobAll);
        model.addAttribute("dept_list",deptAll);

        return "employee/edit";
    }

    @RequestMapping("/employee/edit")
    public String edit(Employee employee){

        //根据id修改对应的字段
        employeeService.update(employee);

        return "redirect:/employee/list";
    }

    @RequestMapping("/employee/topiliang")
    public String toPL(){
        return "employee/pladd";
    }

    @RequestMapping("/employee/piliang")
    public String piliang(MultipartFile file) throws Exception{

        //1.接受上传的文件
        InputStream is = file.getInputStream();
        Workbook wb = new XSSFWorkbook(is);
        List<Employee> emplist=new ArrayList<>();
        Sheet sheet = wb.getSheetAt(0);   //读取sheet 0

        int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名，所以不读
        int lastRowIndex = sheet.getLastRowNum();//当前sheet有多少行

        List<Employee> list = new ArrayList<>();

        for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
            Row row = sheet.getRow(rIndex);
            int cells = row.getPhysicalNumberOfCells();//每一行有多少列

            Employee employee = new Employee();
            Class<? extends Employee> cc = employee.getClass();
            Field[] fields = cc.getDeclaredFields();
            for(int i=0;i<cells;i++){

                fields[i].setAccessible(true);//可以操作被封装的属性
                if(fields[i].getType().getName().equals("java.lang.Integer")){
                    String o = row.getCell(i).getStringCellValue();
                    fields[i].set(employee,Integer.parseInt(o));
                }
                if(fields[i].getType().getName().equals("java.lang.String")){
                    String o = row.getCell(i).getStringCellValue();
                    fields[i].set(employee,o);
                }

            }

            list.add(employee);

        }

        //list这些数据插入数据库
        for(Employee employee : list){
            employeeService.insert(employee);
        }

        return "redirect:/employee/list";
    }

    @RequestMapping("/employee/toshuoming")
    public ResponseEntity<byte[]> downFiles() throws Exception{
        //D:\personal\empfiles 下载这下面的文件

        File parfile = new File("D:\\personal\\empfiles");
        File f = parfile.listFiles()[0];
        String name = f.getName();
        FileInputStream fis = new FileInputStream(f);
        int leng = fis.available();
        byte[] buff = new byte[leng];
        fis.read(buff);

        HttpHeaders headers = new HttpHeaders();//http头信息
        String downloadFileName = new String(name.getBytes("UTF-8"),"ISO-8859-1");//设置编码

        headers.setContentDispositionFormData("attachment", downloadFileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //MediaType:互联网媒介类型  contentType：具体请求中的媒体类型信息
        fis.close();
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(f),headers, HttpStatus.CREATED);
    }
}
